package de.argh.codebook.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import de.argh.codebook.model.ErrorMessage;
import de.argh.codebook.model.ValidationResponse;

@Component
public class ValidationHelper {
  
  public ValidationResponse validateBindingResult(BindingResult result) {
    ValidationResponse res = new ValidationResponse();
    if (result.hasErrors()) {
      res.setStatus("FAIL");
      List<FieldError> allErrors = result.getFieldErrors();
      List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
      for (FieldError objectError : allErrors) {
        errorMesages.add(new ErrorMessage(objectError.getField(), objectError.getField() + "  " + objectError.getDefaultMessage()));
      }
      res.setErrorMessageList(errorMesages);

    } else {
      res.setStatus("SUCCESS");
    }

    return res;
  }
}
